<template>
    <div class="flex_col_start p10 m5 card">
        <label class="flex_center_self">{{ props.name }}</label>
        <div class="flex_row_center mt5">
            <label>MAC地址:</label>
            <el-input v-model="ctx.mac_addr" class="ml5" style="width: 250px;" clearable />
        </div>
        <div class="flex_row_center w100 mt5" style="justify-content: space-between;">
            <label>名称:</label>
            <el-input v-model="ctx.name" class="ml5" style="width: 250px;" clearable />
        </div>
        <div class="flex_row_center w100 mt5" style="justify-content: space-between;">
            <label>备注:</label>
            <el-input v-model="ctx.remark" class="ml5" style="width: 250px;" clearable />
        </div>
        <div class="flex_row_center w100 mt5" style="justify-content: center;">
            <el-button @click="onClickCreate" type="primary">创建</el-button>
        </div>
    </div>
</template>

<script lang="ts" setup>
import { createDevice } from '@/service/device';
import { runAction } from '@/utils/ui';
import { reactive } from 'vue';

interface Props {
    id: number,
    name: string,
}

const props = defineProps<Props>();

interface Ctx {
    name: string,
    mac_addr: string,
    remark: string,
}
const ctx = reactive<Ctx>({
    name: '',
    mac_addr: '',
    remark: ''
});


const emit = defineEmits<{
    created: []
}>();

function isValidMACAddress(mac: string) {
    const macRegex = /^([0-9A-Fa-f]{2}[:-]){5}([0-9A-Fa-f]{2})$/;
    return macRegex.test(mac);
}

async function onClickCreate() {
    let flag = false;
    await runAction('创建', '', async () => {
        if (!isValidMACAddress(ctx.mac_addr)) {
            throw '请输入格式正确的MAC地址';
        }
        if (ctx.name.length == 0) {
            throw '请输入名称';
        }
        await createDevice({
            type_id: props.id,
            name: ctx.name,
            remark: ctx.remark,
            mac_addr: ctx.mac_addr,
        });
        flag = true;
    });
    if (!flag) {
        return;
    }
    emit('created');
}


</script>
